package tool

import (
	"os"
	"path/filepath"
	"slices"
)

// SearchType 定义了搜索模式
type SearchType int

const (
	SearchFiles SearchType = iota // 只搜索文件
	SearchDirs                    // 只搜索文件夹
	SearchAll                     // 搜索所有文件和文件夹
)

func ListFile(dir string, ext string, recursive bool, st SearchType, fullPath bool) ([]string, error) {
	var result []string

	//递归必须是绝对路径
	if recursive {
		fullPath = true
	}

	files, err := os.ReadDir(dir)
	if err != nil {
		return result, err
	}

	for _, f := range files {
		if (f.IsDir() && st == SearchFiles && !recursive) || (!f.IsDir() && st == SearchDirs) {
			continue
		}
		if st != SearchDirs && !f.IsDir() && len(ext) > 0 && filepath.Ext(f.Name()) != ext {
			continue
		}

		v := f.Name()
		if fullPath {
			v = filepath.Join(dir, v)
		}
		if !((st == SearchDirs && !f.IsDir()) || (st == SearchFiles && f.IsDir())) {
			result = append(result, v)
		}
		if recursive && f.IsDir() && !slices.Contains([]string{".", ".."}, f.Name()) {
			ret2, _ := ListFile(filepath.Join(dir, f.Name()), ext, recursive, st, fullPath)
			result = append(result, ret2...)
		}
	}

	return result, nil
}


// 获取windows系统下有几个盘
func getDevices() []string {
	// 遍历字符 'C' 到 'Z'
	var devices []string
	for char := 'C'; char <= 'Z'; char++ {
		d := string(char) + ":"
		if _, err := os.Stat(d); os.IsNotExist(err) {
			break
		}
		devices = append(devices, d)
	}
	return devices
}